﻿using DoNetDrive.AspWebSocke;
using DoNetDrive.AspWebSocke.WebSocketClient;
using DoNetDrive.AspWebSocke.WebSocketServer;
using DoNetDrive.Core.Command;
using DoNetDrive.Core.Command.Text;
using DoNetDrive.Core.Packet;
using Face8280WebSocketServer.DB.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Command
{
    public class JsonCommand : AbstractCommand
    {
        protected object mSendObject;
        protected Action<string> mJsonResult;

        public string Reply { get; set; }

        protected JsonSerializerSettings setting = new JsonSerializerSettings
        {
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore
        };
        public JsonCommand(INCommandDetail cd, object par) : base(cd, null)
        {

            Reply = this.GetType().Name;
            _IsWaitResponse = true;
            _Decompile = new JsonPacketDecompile();

            if (par != null)
            {
                var obj = JObject.Parse(par.ToJson());
                var cmd = "Cmd";
                if (obj.ContainsKey(cmd))
                {
                    obj[cmd] = Reply;
                }
                else
                {
                    obj.Add(cmd, Reply);
                }
                mSendObject = obj;
            }
            // Allocator.OpenConnectorAsync(cd.Connector).Wait();
        }
        /// <summary>
        /// 创建数据包
        /// </summary>
        protected override void CreatePacket()
        {

            var sJson = JsonConvert.SerializeObject(mSendObject, setting);
            _Packet = new JsonPacket(sJson);
            _ProcessStep = 1;
        }
        protected override void CommandNext(INPacket readPacket)
        {
            if (readPacket is JsonPacket)
            {
                var jPck = readPacket as JsonPacket;
                var sJson = jPck.GetJson();
                if (CheckJsonResult(sJson) == true)
                {
                    CommandCompleted();
                }
            }
        }
        /// <summary>
        /// 检查响应数据
        /// </summary>
        /// <param name="sRetJson"></param>
        /// <returns></returns>
        public virtual bool CheckJsonResult(string sRetJson)
        {
            try
            {
                var json = JObject.Parse(sRetJson);
                if (json.Property("reply", StringComparison.OrdinalIgnoreCase) != null && sRetJson.IndexOf(Reply, StringComparison.OrdinalIgnoreCase) > 0)
                {
                    mJsonResult?.Invoke(sRetJson);
                    return true;

                }
                //if (sRetJson.StartsWith("{\"reply\":", StringComparison.OrdinalIgnoreCase)
                //    && sRetJson.IndexOf(Reply, StringComparison.OrdinalIgnoreCase) > 0)
                //{
                //    mJsonResult?.Invoke(sRetJson);
                //    return true;
                //}
            }
            catch (Exception ex)
            {
                SetException(ex);
                CommandError();
                Console.WriteLine(ex.Message);
            }
            return false;
        }

        protected override AbstractCommandStatus_WaitResponse GetStatus_WaitResponse()
        {
            return base.GetStatus_WaitResponse();
        }
        protected override Task SendPacketCore()
        {
            return base.SendPacketCore();
        }
        protected override bool CheckCommandParameter(INCommandParameter value)
        {
            return true;
        }

        protected override void CommandReSend()
        {

        }
        ///// <summary>
        ///// 发送数据包
        ///// </summary>
        ///// <returns></returns>
        //protected async override Task SendPacketCore()
        //{
        //    var packet = _Packet as JsonPacket;
        //    var buf = packet.GetTextPacketData();//发送文本类型数据包
        //    await _Connector.WriteByteBuf(buf);

        //    var binaryBuf = packet.GetBinaryPacketData();//发送二进制类型数据包
        //    if (binaryBuf != null)
        //        await _Connector.WriteByteBuf(binaryBuf);
        //}

        protected override void Release0()
        {

        }
    }
}
